package com.justrun.zjutsystem.zjutsystem.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.justrun.zjutsystem.zjutsystem.entity.Teacher;
import com.justrun.zjutsystem.zjutsystem.mapper.TeacherMapper;
import com.justrun.zjutsystem.zjutsystem.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.channels.Pipe;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ln
 * @Description: ${todo}
 * @date 2020/10/14
 */
public class DemoDataListener extends AnalysisEventListener<Teacher> {

    private static final int BATCH_COUNT = 5;
    //    用作缓存池
    List<Teacher> list = new ArrayList<>();

    private TeacherService teacherService;

    public DemoDataListener() {

    }

    public DemoDataListener(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @Override
    public void invoke(Teacher teacher, AnalysisContext analysisContext) {
        list.add(teacher);
        if (list.size() >= BATCH_COUNT) {
            teacherService.saveBatch(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//      这里也要保存数据，确保最后遗留的数据也存储到数据库
        teacherService.saveBatch(list);
        System.out.println("所有数据解析完成");
    }
}
